package com.koron.css2.newProjectCenter.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.newProjectCenter.bean.PjMaterialBean;
import com.koron.css2.newProjectCenter.bean.query.PjMaterialQueryBean;
import com.koron.css2.newProjectCenter.mapper.PjMaterialMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 工程材料保存
 */
public class PjMaterialSave implements ServerInterface {

    // 金额正则匹配
    private static final String REGEX = "^[0-9]+(\\.[0-9]{1,2})?$";

    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
            List<PjMaterialBean> pjMaterialList = JsonUtils.objectToList(req.getData(), PjMaterialBean.class);
            PjMaterialMapper pjMaterialMapper = factory.getMapper(PjMaterialMapper.class);

            // 将材料编号转化为列表集合
            List<String> pjMaterialNoList = pjMaterialList.stream()
                    .filter(t -> StringUtils.isNotEmpty(t.getMaterialNo()))
                    .map(t -> t.getMaterialNo())
                    .collect(Collectors.toList());
            PjMaterialQueryBean query = new PjMaterialQueryBean();
            query.setMaterialNoList(pjMaterialNoList);
            // 通过材料编号查询出材料单集合
            List<PjMaterialBean> oldPjMaterialList =pjMaterialMapper.selectList(query);
            // 将材料单列表集合转成 MAP
            Map<String, PjMaterialBean> oldPjMaterialMap = oldPjMaterialList.stream().collect(Collectors.toMap(PjMaterialBean::getMaterialNo, Function.identity()));

            StringBuilder stringBuilder = new StringBuilder("");
            for (int i = 0; i < pjMaterialList.size(); i++){
                PjMaterialBean pjMaterial = pjMaterialList.get(i);
                if (StringUtils.isBlank(pjMaterial.getMaterialName())){
                    stringBuilder.append("第" + (i + 1) + "行：材料名称为空 <br/>");
                }
                if (pjMaterial.getPrice() == null){
                    stringBuilder.append("第" + (i + 1) + "行：材料价格为空 <br/>");
                }
                if (pjMaterial.getPrice() != null &&!Objects.toString(pjMaterial.getPrice()).matches(REGEX)){
                    stringBuilder.append("第" + (i + 1) + "行：材料价格只能为数字 <br/>");
                }
                // 通过材料编号查询数据库已存在的材料单
                PjMaterialBean oldPjMaterial = oldPjMaterialMap.get(pjMaterial.getMaterialNo());
                // 如果存在ID ，则修改数据
                if (StringUtils.isNotBlank(pjMaterial.getId())){
                    if (oldPjMaterial != null && !Objects.equals(oldPjMaterial.getId(), pjMaterial.getId())){
                        stringBuilder.append("第" + (i + 1) + "行：系统中已存在" + pjMaterial.getMaterialNo() + "编号的材料 <br/>");
                    }
                } else {
                    if (oldPjMaterial != null && StringUtils.isNotBlank(pjMaterial.getMaterialNo())){
                        stringBuilder.append("第" + (i + 1) + "行：系统中已存在" + pjMaterial.getMaterialNo() + "编号的材料 <br/>");
                    }
                }
            }
            // 存在错误信息
            if (stringBuilder.toString().length() > 0){
                MessageBean errMsg = MessageBean.create(Constant.MESSAGE_INT_FAIL, "工程材料单保存失败", String.class);
                // 返回错误信息
                errMsg.setData(stringBuilder.toString());
                return errMsg;
            }

            // ID为空的材料单转化为集合
            List<PjMaterialBean> insertPjMaterialList = pjMaterialList.stream()
                    .filter(t -> StringUtils.isBlank(t.getId()))
                    .collect(Collectors.toList());

            // ID 不为空的材料单转化为集合
            List<PjMaterialBean> updatePjMaterialList = pjMaterialList.stream().filter(t -> StringUtils.isNotBlank(t.getId())).collect(Collectors.toList());
            // 批量添加材料单
            if (insertPjMaterialList.size() > 0){
                insertPjMaterialList.stream().forEach(t -> t.setCreateInfo(userInfo));
                pjMaterialMapper.batchAddPjMaterial(insertPjMaterialList);
            }
            // 修改材料单
            if (updatePjMaterialList.size() > 0){
                pjMaterialMapper.updatePjMaterial(updatePjMaterialList.get(0));
            }
            return MessageBean.create(Constant.MESSAGE_INT_SUCCESS,"工程材料单保存成功",null);
        } catch (Exception e) {
            logger.error("工程材料单保存失败",e);
        }
        return MessageBean.create(Constant.MESSAGE_INT_FAIL,"工程材料单保存失败",null);
    }
}
